package com.wsc.wisdomchinaqinghe.activitity.fourmodule;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wsc.wisdomchinaqinghe.R;
import com.wsc.wisdomchinaqinghe.Tools.AbPermissionUtils;
import com.wsc.wisdomchinaqinghe.Tools.BitmapUtils;
import com.wsc.wisdomchinaqinghe.Tools.JsonTools;
import com.wsc.wisdomchinaqinghe.Tools.Tools;
import com.wsc.wisdomchinaqinghe.activitity.baseactivity.BaseActivity;
import com.wsc.wisdomchinaqinghe.callback.ContributorView;
import com.wsc.wisdomchinaqinghe.constant.Constant;
import com.wsc.wisdomchinaqinghe.javaBean.RespObj;
import com.wsc.wisdomchinaqinghe.presenter.ContributorPresenter;
import com.wsc.wisdomchinaqinghe.view.MyToast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 企业发布页面
 * Created by ${wangtao} on 2017/3/6.
 */

public class CompanyPublishActivity extends BaseActivity implements View.OnClickListener,ContributorView {
    private EditText fragment_qyfb_name, fragment_qyfb_phone, fragment_qyfb_LYname, fragment_qyfb_qymingcheng,
            fragment_qyfb_officem, fragment_qyfb_sellm, fragment_qyfb_compatym, fragment_qyfb_address, fragment_qyfb_content;
    private Button fragment_qyfb_enter;
    private ImageView fragment_qyfb_back;//返回
    private ImageView one_one, one_two, one_three;
    private RelativeLayout fragment_qyfb_RLTSex;
    private TextView fragment_qyfb_sex;
    private Context context;
    private PopupWindow popupWindow;
    private View mpopupWindowView;
    private TextView tv_cancel;
    private TextView tv_man;
    private TextView tv_woman;
    private TextView tv_cancelPhone;
    private TextView tv_takephoto;
    private TextView tv_photo;
    private TextView tv_headtitle;
    private PopupWindow popupWindowPhone;
    private View mpopupWindowViewPhone;
    private int imageFlag = 1;
    private Bitmap photo;
    private ContributorPresenter contributorPresenter;
    private final String UPLOADPICTUREFLAG="UPLOADPICTUREFLAG";
    private String resultParam="";
    private String uid;
    private MyToast myToast;
    private String cidRequest;
    private String uidRequest;
    private String nameRequest;
    private String sexRequest;
    private String mobileRequest;
    private String company_nameRequest;
    private String buinding_nameRequest;
    private String scaleRequest;
    private String rangeRequest;
    private String websiteRequest;
    private String addrRequest;
    private String introRequest;
    private final String RELEASECOMPANYFLAG="RELEASECOMPANYFLAG";
    private String cidNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.companypublish_layout);
        context = this;
        myToast=new MyToast(context);
        cidNumber=getIntent().getStringExtra("cid");
        uid=Tools.getSharedPreferencesStrings(Constant.SharePreferenceUserid,"",context);
        myToast=new MyToast(context);
        contributorPresenter=new ContributorPresenter(this,context);
        initView();
        initPopupWindow();
        initPopupWindowPhone();
    }

    private void initView() {
        fragment_qyfb_name = (EditText) findViewById(R.id.fragment_qyfb_name);
        fragment_qyfb_phone = (EditText) findViewById(R.id.fragment_qyfb_phone);
        fragment_qyfb_LYname = (EditText) findViewById(R.id.fragment_qyfb_LYname);
        fragment_qyfb_qymingcheng = (EditText) findViewById(R.id.fragment_qyfb_qymingcheng);
        fragment_qyfb_officem = (EditText) findViewById(R.id.fragment_qyfb_officem);
        fragment_qyfb_sellm = (EditText) findViewById(R.id.fragment_qyfb_sellm);
        fragment_qyfb_compatym = (EditText) findViewById(R.id.fragment_qyfb_compatym);
        fragment_qyfb_address = (EditText) findViewById(R.id.fragment_qyfb_address);
        fragment_qyfb_content = (EditText) findViewById(R.id.fragment_qyfb_content);
        fragment_qyfb_enter = (Button) findViewById(R.id.fragment_qyfb_enter);
        one_one = (ImageView) findViewById(R.id.one_one);
        one_two = (ImageView) findViewById(R.id.one_two);
        one_three = (ImageView) findViewById(R.id.one_three);
        fragment_qyfb_RLTSex = (RelativeLayout) findViewById(R.id.fragment_qyfb_RLTSex);
        fragment_qyfb_sex = (TextView) findViewById(R.id.fragment_qyfb_sex);
        fragment_qyfb_back = (ImageView) findViewById(R.id.regist_back);

        fragment_qyfb_enter.setOnClickListener(this);
        one_one.setOnClickListener(this);
        one_two.setOnClickListener(this);
        one_three.setOnClickListener(this);
        fragment_qyfb_RLTSex.setOnClickListener(this);
        fragment_qyfb_back.setOnClickListener(this);
        tv_headtitle=(TextView) findViewById(R.id.tv_headtitle);
        tv_headtitle.setText("企业发布");
    }

    /**
     * 初始化popupwindow
     */
    private void initPopupWindow() {
        mpopupWindowView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.sexinfo, null);
        popupWindow = new PopupWindow(mpopupWindowView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);// 全屏显示，将内容设置在底部
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        tv_cancel = (TextView) mpopupWindowView.findViewById(R.id.tv_cancelsex);
        tv_cancel.setOnClickListener(this);
        tv_woman = (TextView) mpopupWindowView.findViewById(R.id.tv_takephotosex);
        tv_woman.setOnClickListener(this);
        tv_man = (TextView) mpopupWindowView.findViewById(R.id.tv_photosex);
        tv_man.setOnClickListener(this);
    }

    /**
     * 初始化popupwindow
     */
    private void initPopupWindowPhone() {
        mpopupWindowViewPhone = LayoutInflater.from(getApplicationContext()).inflate(R.layout.headinfo, null);
        popupWindowPhone = new PopupWindow(mpopupWindowViewPhone, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);// 全屏显示，将内容设置在底部
        popupWindowPhone.setFocusable(true);
        popupWindowPhone.setBackgroundDrawable(new BitmapDrawable());

        tv_cancelPhone = (TextView) mpopupWindowViewPhone.findViewById(R.id.tv_cancel);
        tv_cancelPhone.setOnClickListener(this);
        tv_takephoto = (TextView) mpopupWindowViewPhone.findViewById(R.id.tv_takephoto);
        tv_takephoto.setOnClickListener(this);
        tv_photo = (TextView) mpopupWindowViewPhone.findViewById(R.id.tv_photo);
        tv_photo.setOnClickListener(this);
    }

    @Override
    public void onLoadContributorStart(String flag) {
        if (flag.equals(UPLOADPICTUREFLAG)) {
            fragment_qyfb_enter.setEnabled(false);
        }
    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            //发送验证码
            if (flag.equals(UPLOADPICTUREFLAG)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object message=respObj.getMessage();
                if (code.equals("200") && message!=null) {
                    String jsonMessage=JsonTools.objectToJsonString(message);
                    List<String> list=JsonTools.jsonStringToList(jsonMessage,String.class);
                    if(list!=null && list.size()>0)
                    {
                        String picRequest="";
                        for(String pic:list)
                        {
                            picRequest+=pic;
                            picRequest+=",";
                        }
                        contributorPresenter.getReleaseCompany(cidRequest,uidRequest,nameRequest,sexRequest,mobileRequest
                                ,company_nameRequest,buinding_nameRequest,scaleRequest,rangeRequest,websiteRequest,addrRequest,introRequest,picRequest,RELEASECOMPANYFLAG);
                    }
                } else {
                    myToast.showShort("上传图片失败");
                }
            }else if(flag.equals(RELEASECOMPANYFLAG))
            {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object message=respObj.getMessage();
                if (code.equals("200") && message!=null) {
                    myToast.showShort("发布成功");
                    Intent intent=getIntent();
                    setResult(1,intent);
                    finish();
                }else
                {
                    myToast.showShort("操作失败");
                }
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoadContributorComplete(String flag) {
        if (flag.equals(UPLOADPICTUREFLAG)) {
            fragment_qyfb_enter.setEnabled(true);
        }
    }

    @Override
    public void onLoadContributorError(String error, String flag) {

    }

    /**
     * @param v 处理点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_qyfb_enter:
                String sex_id = fragment_qyfb_sex.getText().toString();
                String sexid = new String();

                if (sex_id != null) {
                    if (sex_id.equals("男")) {
                        sexid = "1";
                    } else if (sex_id.equals("女")) {
                        sexid = "0";
                    }
                }

                charge_Data(cidNumber,uid,fragment_qyfb_name.getText().toString(), sexid, fragment_qyfb_phone.getText().toString(),
                        fragment_qyfb_qymingcheng.getText().toString(), fragment_qyfb_LYname.getText().toString(),
                        fragment_qyfb_officem.getText().toString(), fragment_qyfb_sellm.getText().toString(),
                        fragment_qyfb_compatym.getText().toString(), fragment_qyfb_address.getText().toString(),fragment_qyfb_content.getText().toString(),resultParam);
                break;
            case R.id.one_one:
                imageFlag = 1;
                View view = getWindow().peekDecorView();
                if (view != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.one_one), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            case R.id.one_two:
                imageFlag = 2;
                View view1 = getWindow().peekDecorView();
                if (view1 != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view1.getWindowToken(), 0);
                }
                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.one_one), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            case R.id.one_three:
                imageFlag = 3;
                View view2 = getWindow().peekDecorView();
                if (view2 != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view2.getWindowToken(), 0);
                }
                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.one_one), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            case R.id.fragment_qyfb_RLTSex:
                View view3 = getWindow().peekDecorView();
                if (view3 != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view3.getWindowToken(), 0);
                }
                if (!popupWindow.isShowing()) {
                    popupWindow.showAtLocation(findViewById(R.id.fragment_qyfb_RLTSex), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindow.dismiss();
                }
                break;
            case R.id.tv_cancelsex:
                popupWindow.dismiss();
                break;
            // woman
            case R.id.tv_takephotosex:
                popupWindow.dismiss();
                fragment_qyfb_sex.setText("女");
                break;
            // man
            case R.id.tv_photosex:
                popupWindow.dismiss();
                fragment_qyfb_sex.setText("男");
                break;
            case R.id.regist_back:
                finish();
                break;
            // 取消点击事件
            case R.id.tv_cancel:
                popupWindowPhone.dismiss();
                break;
            // 拍照点击事件
            case R.id.tv_takephoto:
                popupWindowPhone.dismiss();
                try {
                    AbPermissionUtils.requestPermissionsResult(this, 1
                            , new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                            }
                            , new AbPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {

                                    Uri uri = getUri();
                                    Intent intent = new Intent();
                                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//将拍取的照片保存到指定URI
                                    startActivityForResult(intent,6);
                                }

                                @Override
                                public void onPermissionDenied() {

                                }
                            });
                }catch (Exception e)
                {
                    myToast.showShort("拍照失败");
                }

                break;
            // 用户相册点击事件
            case R.id.tv_photo:
                popupWindowPhone.dismiss();
                try{
                    AbPermissionUtils.requestPermissionsResult(this, 1
                            , new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                            }
                            , new AbPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {
                                    Intent intentphoto = new Intent(Intent.ACTION_PICK, null);
                                    intentphoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                    startActivityForResult(intentphoto, 1);
                                }

                                @Override
                                public void onPermissionDenied() {

                                }
                            });
                }catch (Exception e)
                {
                    myToast.showShort("读取相册失败");
                }
                break;

        }
    }


    private void charge_Data(String cid,String uid,String name, String sex,String mobile, String company_name,String building_name,String scale,String range,String website,String addr,String intro,String img) {
       if(mobile.isEmpty())
       {
           myToast.showShort("手机号为空");
       }else
       {
           if(Tools.isMobile(mobile))
           {
               if(name.isEmpty() || sex.isEmpty() || company_name.isEmpty() || addr.isEmpty() || img.isEmpty())
               {
                   myToast.showShort("请填写完整信息");
               }else
               {
                   contributorPresenter.getUploadCommonPicList(img,UPLOADPICTUREFLAG);
                   cidRequest=cid;
                   uidRequest=uid;
                   nameRequest=name;
                   sexRequest=sex;
                   mobileRequest=mobile;
                   company_nameRequest=company_name;
                   buinding_nameRequest=building_name;
                   scaleRequest=scale;
                   rangeRequest=range;
                   websiteRequest=website;
                   addrRequest=addr;
                   introRequest=intro;
               }

           }else{
               myToast.showShort("手机号码不合法");
           }
       }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 从相册里面获取
            case 1:
                if (data != null && data.getData() != null) {
                    startPhotoZoom(data.getData());
                }
                break;
            // 裁剪
            case 2:
                if (data != null) {
                    setPicToView(data);
                }
                break;
            // 拍照
            case 6:
                startPhotoZoomCut();
                break;
        }
    }
    private Uri getUri() {
        try{
            File cacheDir;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                cacheDir = new File(Environment.getExternalStorageDirectory(), Constant.wsc_photo);
            else
                cacheDir = context.getCacheDir();
            if (!cacheDir.exists())
                cacheDir.mkdirs();

            File path = new File(cacheDir, "");
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File(path, "company.jpg");
            //由于一些Android 7.0以下版本的手机在剪裁保存到URI会有问题，所以根据版本处理下兼容性
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return FileProvider.getUriForFile(context, "com.wsc.wisdomchinaqinghe.fileprovider", file);
            } else {
                return Uri.fromFile(file);
            }
        }catch (Exception e)
        {
            return null;
        }

    }

    /**
     * @param uri
     * @Description 裁剪图片
     * @author jaily.zhang
     */
    private void startPhotoZoom(Uri uri) {
        try {
                 /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
		 * yourself_sdk_path/docs/reference/android/content/Intent.html
		 * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的，小马不懂C C++
		 * 这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么 制做的了...吼吼
		 */
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 0.8);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 2);
        } catch (Exception e) {

        }
    }

    /**
     * 裁剪图片从拍照
     */
    private void startPhotoZoomCut()
    {
        try {
            Uri uri = getUri();
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            intent.setDataAndType(uri , "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 0.8);
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("scale", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, getUri());
            intent.putExtra("return-data", true);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("noFaceDetection", true);

            //将存储图片的uri读写权限授权给剪裁工具应用
            List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            startActivityForResult(Intent.createChooser(intent, "选择剪裁工具"), 2);
        } catch (Exception e) {

        }
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            photo = extras.getParcelable("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            if (photo != null) {
                try {
                    // Drawable drawable = new BitmapDrawable(photo);

                    /**
                     * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，QQ头像上传采用的方法跟这个类似
                     */

                    int options = 70;
                    photo.compress(Bitmap.CompressFormat.JPEG, options, stream);
                    byte[] b = stream.toByteArray();// 将图片流以字符串形式存储下来
                    // 大于2KB
                    while (b.length > 5 * 1024) {
                        stream.reset();// 清空流
                        options -= 10;
                        photo.compress(Bitmap.CompressFormat.JPEG, options, stream);
                        b = stream.toByteArray();
                    }

                    Message message=new Message();
                    message.what=imageFlag;
                    mHandler.sendMessage(message);

                } catch (Exception e) {

                } finally {
                    try {
                        // 关闭流
                        stream.flush();
                        stream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
    }

    // handler 消息处理
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Drawable drawable = new BitmapDrawable(photo);
                    one_one.setImageDrawable(drawable);
                    one_two.setVisibility(View.VISIBLE);
                    resultParam= BitmapUtils.bitmapToBase64(photo);
                    break;
                case 2:
                    Drawable drawable2 = new BitmapDrawable(photo);
                    one_two.setImageDrawable(drawable2);
                    one_three.setVisibility(View.VISIBLE);
                    resultParam+=",";
                    resultParam+= BitmapUtils.bitmapToBase64(photo);
                    break;
                case 3:
                    Drawable drawable3 = new BitmapDrawable(photo);
                    one_three.setImageDrawable(drawable3);
                    resultParam+=",";
                    resultParam+= BitmapUtils.bitmapToBase64(photo);
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(photo!=null && !photo.isRecycled())
        {
            photo.isRecycled();
            photo=null;
        }
    }

}
